using UnityEngine;

public class ArcherBattleState : EnemyState
{
    private new Archer Enemy => (Archer)base.Enemy;
    private int moveDirection;

    public ArcherBattleState(Enemy enemy, string animName) : base(enemy, animName) { }

    public override void Enter()
    {
        base.Enter();
        if (PlayerManager.Instance.Player.Stats.IsDead)
            StateMachine.ChangeTo(Enemy.IdleState);
    }

    public override void Update()
    {
        base.Update();
        if (Enemy.Player)
        {
            stateTimer = Enemy.battleTime;
            if (Vector3.Distance(Enemy.Player.transform.position, Enemy.transform.position) < Enemy.safeDistance)
            {
                if (CanJump())
                    StateMachine.ChangeTo(Enemy.JumpState);
                else
                    StateMachine.ChangeTo(Enemy.CloseAttackState);
            }
            if (Vector3.Distance(Enemy.transform.position, Enemy.Player.transform.position) <= 15 && CanAttack())
            {
                StateMachine.ChangeTo(Enemy.AttackState);
            }
        }
        else
        {
            if (stateTimer <= 0)
            {
                StateMachine.ChangeTo(Enemy.IdleState);
            }
        }
        BattleFlipControl();
    }

    private void BattleFlipControl()
    {
        if (Enemy.Player.transform.position.x > Enemy.transform.position.x && Enemy.FacingDirection == -1)
        {
            Enemy.Flip();
        }
        else if (Enemy.Player.transform.position.x < Enemy.transform.position.x && Enemy.FacingDirection == 1)
        {
            Enemy.Flip();
        }
    }

    private bool CanAttack()
    {
        if (Time.time >= Enemy.lastTimeAttacked + Enemy.attackCooldown)
        {
            Enemy.attackCooldown = Random.Range(Enemy.minAttackCooldown, Enemy.maxAttackCooldown);
            Enemy.lastTimeAttacked = Time.time;
            return true;
        }
        return false;
    }

    public bool CanJump()
    {
        if (!Enemy.GroundBehindCheck() || Enemy.WallBehindCheck())
        {
            return false;
        }
        if (Time.time >= Enemy.LastTimeJumped + Enemy.JumpCooldown)
        {
            Enemy.LastTimeJumped = Time.time;
            return true;
        }
        return false;
    }
}
